package com.nondo.rdp.finance.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.finance.domain.Setting;
import com.nondo.rdp.finance.repository.SettingRepository;
import com.nondo.rdp.finance.service.SettingService;

@Service
@Transactional
public class SettingServiceImpl implements SettingService {

	@SuppressWarnings("rawtypes")
	@Autowired
	RedisTemplate redisTemplate;//加泛型无法注入

	@Autowired
	SettingRepository settingRepository;

	public Setting findByName(String name) {
		@SuppressWarnings("unchecked")
		ValueOperations<String, List<Setting>> operations = redisTemplate.opsForValue();
		List<Setting> settingList = operations.get("sys_setting");
		if (settingList == null) {
			settingList = this.settingRepository.findAll();
			operations.set("sys_setting", settingList);
		}
		for (Setting setting : settingList) {
			if (setting.getName().equals(name)
					&& setting.getDelFlag().equals("0")) {
				return setting;
			}
		}
		return this.settingRepository.findByName(name);
	}

	public String isHideBuyButton(String version) {
		String isHide = null;
		Setting setting = findByName(version
				+ StatusConstant.HIDE_BUY_HEY);
		if (setting == null) {
			isHide = StatusConstant.SHOW_BUY_BUTTON;
		} else {
			isHide = setting.getValue();
		}
		return isHide;
	}

	@Override
	public Setting save(Setting setting) {
		@SuppressWarnings("unchecked")
		ValueOperations<String, List<Setting>> operations = redisTemplate
				.opsForValue();
		setting = this.settingRepository.save(setting);
		List<Setting> settingList = this.settingRepository.findAll();
		operations.set("sys_setting", settingList);
		return setting;
	}

	@Override
	public Setting findOne(Long id) {
		return this.settingRepository.findOne(id);
	}

	@Override
	public List findAll() {
		return this.settingRepository.findAll();
	}
	
	public boolean judgeTaskStatus() {
		Setting setting = findByName("TASK_STATUS");
		if (setting != null && "0".equals(setting.getValue()))
			return true;
		return false;
	}
}
